package com.yorick.chat.service;

import com.google.protobuf.InvalidProtocolBufferException;
import com.yorick.chat.protobuf.Message;
import com.yorick.login.entity.Account;
import com.yorick.netty.WebSocketServerHandler;
import com.yorick.netty.messageListener.LogicService;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.AttributeKey;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.Optional;

@Service("1")
public class ChatService extends WebSocketServerHandler implements LogicService {

    @Override
    public void task(byte[] data, ChannelHandlerContext ctx) throws InvalidProtocolBufferException {
        String account = ctx.channel().attr(AttributeKey.valueOf("account")).get().toString();
        Message.C2SMessage message = Message.C2SMessage.parseFrom(data);
        Channel channel = findChannel(message.getAccount());
        Optional<Channel> optional = Optional.ofNullable(channel);
        optional.ifPresent(channel1 -> {
            Message.S2CMessage res = Message.S2CMessage.newBuilder()
                    .setMessage(message.getMessage())
                    .setAccount(account)
                    .build();
            channelSend(channel1, 2, res.toByteArray());
        });
    }

    public Channel findChannel(String account){
        Channel channel = Account.channels.get(account); // map
        if (ObjectUtils.isEmpty(channel)) {
            return null;
        }
        return channels.find(channel.id());

    }
}
